package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.EnumException;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void sendCode(String phone) {
        String key = RedisConstant.APP_LOGIN_PREFIX+phone;
        Boolean hasKey = redisTemplate.hasKey(key);
        //1.先看有没有在redis中存phone
        if (hasKey){
            //redisTemplate获取剩余时间-3
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //获取300秒-1
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //获取60秒-2
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;
            if(appLoginCodeTtlSec-expire<appLoginCodeResendTimeSec){
                throw new EnumException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //1.生成验证码
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String code = stringBuilder.toString();
        System.out.println("验证码 = " + code);
        //2.存储到redis中[有效期]
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        //接收前端手机号和验证码
        String key = RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);
        //校验
        if (code==null||!code.equals(loginVo.getCode())){
            throw new EnumException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //正确->登录或者注册
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        System.out.println("userInfo = " + userInfo);
        if (userInfo==null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            //佚名+手机号后四位
            userInfo.setNickname("佚名"+loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            //注册
            userInfoService.save(userInfo);
        }
        //判断用户是否可用
        if (userInfo.getStatus()== BaseStatus.DISABLE){
            throw new EnumException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //可用,jwt->token
        String token = JwtUtil.createToToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }

    @Override
    public UserInfoVo info(String accessToken) {
        Claims claims = JwtUtil.parseToken(accessToken);
        Integer userId = (Integer) claims.get("userId");
        //2.根据userId查询
        UserInfo userInfo = userInfoService.getById(userId);
        //3.封装
        return new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
    }

}
